--- 采样器
local sampler = {}
local math = math
local Util = require("skywalking.util")
local ngx = ngx
local pcall = pcall

--- 随机+URL过滤采样器
--- @param sample_ratio 采样比例:0 ~ 10000
--- @param white_url_map url白名单
--- @param black_url_map url黑名单
function sampler.randomUrlFilterSampler(sample_ratio, white_url_map, black_url_map)
    white_url_map = white_url_map or {}
    black_url_map = black_url_map or {}

    return function(tracing_context)
        local url = ngx.var.uri
        if black_url_map[url] then
            return false
        end

        if white_url_map[url] then
            return true
        end

        -- pcall(Util.set_randomseed)
        local sample_ratio_cur = math.random(0, 10000)
        -- math.randomseed(ngx.time())
        if sample_ratio_cur <= sample_ratio then
            return true
        end
        return false
    end
end

--- @param host_sample_ratio_config 采样比例-host配置
--- @param white_url_map url白名单
--- @param black_url_map url黑名单
--- @param default_sample_ratio 默认采样率
function sampler.randomRandomHostSampler(sample_ratio_config, white_url_map, black_url_map, default_sample_ratio)
    white_url_map = white_url_map or {}
    black_url_map = black_url_map or {}
    sample_ratio_config = sample_ratio_config or {}
    default_sample_ratio = default_sample_ratio or 1

    return function(tracing_context)
        local url = ngx.var.uri
        if black_url_map[url] then
            return false
        end

        if white_url_map[url] then
            return true
        end

        local sample_ratio = sample_ratio_config[ngx.var.host or ""] or default_sample_ratio

        -- pcall(Util.set_randomseed)
        local sample_ratio_cur = math.random(0, 10000)
        -- math.randomseed(ngx.time())
        if sample_ratio_cur <= sample_ratio then
            return true
        end
        return false
    end
end

--- 随机采样器
--- @param sample_ratio 采样比例:0 ~ 10000
function sampler.randomSampler(sample_ratio)
    return function(tracing_context)
        local sample_ratio_cur = math.random(0, 10000)
        -- math.randomseed(ngx.time())
        -- Util.set_randomseed()
        if sample_ratio_cur <= sample_ratio then
            return true
        end
        return false
    end
end

--- 固定采样器
function sampler.constSampler(bool)
    return function(tracing_context)
        return bool
    end
end

-- URL采样器
function sampler.urlFilterSampler(white_map)
    return function(tracing_context)
        local url = ngx.var.request_uri
        if white_map[url] then
            return true
        end

        return true
    end
end

--- @TODO 根据traceID做hash采样（用murmurhash）
function sampler.traceIDSampler(sample_ratio, trace_id)
end

return sampler
